package org.lzz.controller;

import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.lzz.pojo.Result;
import org.lzz.pojo.User;
import org.lzz.service.UserService;
import org.lzz.utils.JwtUtil;
import org.lzz.utils.Md5Util;
import org.lzz.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 注册
    @PostMapping("/register")
    // \S:非空字符
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
        // String token = Md5Util.getMD5String("12345");
        // log.info("12345密码加密："+Md5Util.getMD5String("12345"));
        // 查询用户
        User u = userService.findByUserName(username);
        if(u==null){
            log.info("注册成功");
            // 未被占用
            // 注册
            userService.register(username,password);
            return Result.success();
        }else{
            log.info("用户名已被占用");
            // 占用
            return Result.error("用户名已被占用");
        }
    }

    // 登录
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
        // 根据用户名查询用户
        User u = userService.findByUserName(username);
        // 判断用户是否存在
        if(u==null){
            return Result.error("用户名不存在");
        }
        // 判断密码是否正确,此时u中的密码是密文形式的
        if(Md5Util.getMD5String(password).equals(u.getPassword())){
            // 登录成功
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",u.getId());
            claims.put("username",u.getUsername());
            String token = JwtUtil.getToken(claims);
            // 把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,30, TimeUnit.DAYS);
            // operations.set(token,token,12, TimeUnit.HOURS);
            log.info("登录成功，将token存入redis中");
            // TODO:若是同一用户在未修改密码的情况下，多次登录生成的多个token怎么解决？？？
            // TODO:多次登录会生成多个token【待优化】
            // 因为key【token】相同，所以旧的token就被覆盖了
            return Result.success(token);
        }
        log.info("密码错误，登录失败");
        return Result.error("密码错误");
    }

    // 获取当前登录用户详细信息
    // 从token中获取username
    @GetMapping("/userInfo")
    public Result<User> userInfo(/* @RequestHeader(name = "Authorization") String token */){
        // 根据用户名查询用户
        // String username = (String) JwtUtil.parseToken(token).get("username");
        log.info("511");
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        // 想要输出数据信息，需要使用占位符`{}`
        log.info("用户名:{}",username);
        // String username = (String) ThreadLocalUtil.get().get("username");
        User user = userService.findByUserName(username);
        log.info("用户信息:{}",user);
        return Result.success(user);
    }

    // 更新用户基本信息
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        // 根据id查找用户更新数据
        userService.update(user);
        return Result.success();
    }

    // 更新用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    // 更改密码
    // TODO:修改的密码应该也要进行参数校验
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        // 1. 校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(newPwd.length()<5||newPwd.length()>16){
            return Result.error("密码得是5~16位非空字符");
        }

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要参数");
        }

        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        if(!user.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码填写不正确");
        }

        if(!newPwd.equals(rePwd)){
            return Result.error("两次填写的新密码不一致");
        }


        // 2. 校验通过，密码更新
        userService.updatePwd(newPwd);
        // 删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);

        return Result.success();
    }
}
